#ifndef _RADS_H_
#define _RDAS_H_
#include <cstdlib>
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <stdarg.h>
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
#include <signal.h>
#include <csignal>
#include <cmath>
#include <map>
#include <limits>
#include <fstream>
#include <iomanip>
#include <regex>

// for md5 hash_code
#include <openssl/md5.h>
#include <openssl/evp.h>

/*
#define DEV_RELEASE
#define DEV_COOPER
#define DEV_LOCAL
 */
#define DEV_RELEASE
#define PROTOCOL_REGEX_PATTERN      R"(^##\d+(,\d+)*$)"
// 1.车辆模式及设备
#define KTV_SN 				        "1500016"
#define KTV_SNS 				    "1500000"

#define RTK_LIKE                        1       //1用激光，2用RTK
#define AUTO_DISRANCE                   2.0      //踩点距离
#define HEADING_THRESHOLD               15       //踩点角度
#define DRIVE_DISRANCE                  1.1     //跑点切换点距离
#define DRIVE_DISRANCE_LAST             1.0      //跑点距离最后一个点距离结束
#define RTK_DISRANCE             1.038     //RTK极限距离
#define SPEED_CHANGE_INTERVAL    25 
#define API_CHANGE_INTERVAL    50    
#define MAXSPEED                 15
#define SPEED                    5
#define DBNAME                    "/home/argo/catkin_ws/src/rads-master/sqlitedata/car.db"
// 轮中心距，单位是米
#define WHEEL_BASE_WIDTH 	        1.4
#define SERIAL_INTERFACE1           "/dev/ttyUSB1"    // mcu  ttyUSB1
#define SERIAL_INTERFACE2           "/dev/ttyUSB2"    // rtk  ttyUSB2
// XOR加密非常不安全!!!
#define XOR_CIPHER_CODE             "xorradscipher"
// 2.RTK配置相关
#define GPYBM_LENGTH	 	        24
#define PREFIX_GPYBM 		        "$GPYBM"
#define RTK_DEVICE 			        SERIAL_INTERFACE2
#define RTK_CHECK_SEC 		        1
#define DIFF_DATA_LEN 		        2048
#define STATION_MASTER_SLAVE_LEN     1.0
// 3.千寻配置相关
#define QX_SERVER 			        "203.107.45.154"
#define QX_PORT 			        8002
#define QX_MOUNT 			        "AUTO"
#define QX_USER 			        "qxwfue0015"
#define QX_USERPASS 		        "bb4c867"
#define ICY_200_OK 			        "ICY 200 OK"
#define SINO_K823 			        0
#define SINO_K827 			        1
// 4.云服务器通信相关
#ifdef DEV_RELEASE
    #define CLOUD_SERVER 	        "47.99.130.112"
    #define CLOUD_PORT 		        10002
#elif defined(DEV_COOPER)
    #define CLOUD_SERVER 	        "192.168.110.172"
    #define CLOUD_PORT 		        8080
#else
    #define CLOUD_SERVER 	        "192.168.8.165"
    #define CLOUD_PORT 		        8080
#endif
#define CLOUD_USERNAME 		         KTV_SNS
#define CLOUD_PASSWORD 		        "123456"
// 5.驱动串口(与下位机通信)
#define DRIVE_DEVICE 		        SERIAL_INTERFACE1
#define DRIVE_CHECK_SEC 	        1        // 驱动检测时间/单位秒
#define PROTOCOL_HEAD0		        0xff
#define PROTOCOL_HEAD1		        0xfe
#define DRIVE_FULL_SIZE	            27       // 全协议长度
#define DRIVE_BUFFER_SIZE	        25       // 这里是不是包含帧头0xff 0xfe,特别注意
#define DRIVE_BUF_XOR_SIZE	        24       // xor校验范围（biye0-byte23,从len开始,校验长度:24）
#define RADAR_DATA_SIZE 	        8
#define EXTEND_DATA_SIZE 	        4
#define HEARTBEAT_TIMEOUT	        200		// 心跳侦测毫秒级，200ms
#define WRITE_INTERVAL_MS           10      // 数据下发的时候,发送间隔时间10ms
// 6.ros服务相关
#define ROSMASTER_URI 		        "http://localhost:11311"
#define CHECK_INTERVAL		        5
#define PACKAGE_NAME		        "rads"
// 7.云端API的接口调用
#define CLOUD_API_URL               "http://apiautopilot.niyouduo.com"
#define CLOUD_API_ROUTE		        "/business/PadCommand"
// 上传地图
#define CLOUD_API_UPFILE            "/PostUploadVMapFile"
// 上传点集
#define CLOUD_API_UPPOINT           "/PostVRoutePoints"
// 下载地图
#define CLOUD_API_MAP_DOWN          "/DownloadMapInfo"
// 下载轨迹
#define CLOUD_API_PATH_DOWN         "/DownloadRouteInfo"
// 提交预览
#define CLOUD_API_PATH_UPLOAD       "/UploadRouteInfo"
// 上传开机点
#define CLOUD_API_POSE_UPLOAD       "/UploadPoseInfo"
// 获取车载服务版本号
#define CLOUD_RADS_VERSION          "/RadsVersion"
// 申请建图，下位机就绪状态
#define CLOUD_API_MAP_READY_STATE   "/UpdateVMapBuildState"
// 上传地图之前，通知size
#define CLOUD_API_MAP_STATE         "/UpdateVMapUploadState"
// 上传进度值
#define CLOUD_API_TASK_PROGRESS     "/UpdateVehicleTaskProcess"
// 8.rosnode节点服务名称
#define NODE_DRIVE			        "radsdrive"
#define NODE_RTK			        "radsrtk"
#define NODE_TBOX			        "radstbox"
#define NODE_GUARD			        "radsguard"
#define NODE_SLAM			        "radsslam"
#define NODE_MAP			        "radsmap"
#define NODE_API			        "radsapi"
#define NODE_BUSINESS		        "radsbuiness"
#define NODE_DATABASE		        "radsdatabase"
// 9.可执行程序的名称
#define NODE_DRIVE_EXECU	        "rads_drive"
#define NODE_RTK_EXECU		        "rads_rtk"
#define NODE_TBOX_EXECU		        "rads_tbox"
#define NODE_GUARD_EXECU	        "rads_guard"
#define NODE_SLAM_EXECU		        "rads_slam"
#define NODE_MAP_EXECU              "rads_map"
#define NODE_API_EXECU		        "rads_api"
#define NODE_BUSINESS_EXECU	        "rads_business"
#define NODE_DATABASS_EXECU	        "rads_database"
// 10.
#define MAP_PCD_TEST                "/home/jpc/ws/pcd/wz3.pcd"
#define MAP_PCD_SAVE                "/home/jpc/ws/pcd/"
// PCD文件上传大小的限制（Mb)
#define FILE_SIZE_LIMIT             1000
#define MINIMUM_VALUE               1e-9F
#define QUEUE_SIZE                  1000

/* * * * * * NetCmdObsolete [老的协议模式定义:NetCmdObsolete] * * * * * */
#define CMDO_REMOTE_CONTROL			1			// 遥控模式
#define CMDO_FOLLOW_ME				2			// 跟随模式
#define CMDO_DEFENSIVE_FORWARD		3			// 防御式向前模式
#define CMDO_RETURN_MODEL			4			// 返航模式
#define CMDO_DISPATCH_NORMAL		5			// 日常调度(图线点)
#define CMDO_DISPATCH_RETURN		6			// 返航调度(图线点)
#define CMDO_HORSE_FLYING			7			// 马踏飞燕(为任意点导航采集可行驶路面点集)
#define CMDO_TEMP_PARKING			8			// 临时停车
#define CMDO_EMERGENCY_BRAKING		9			// 紧急制动
#define CMDO_MAP_BUILD				10			// 请求建图
#define CMDO_MAP_UPLOAD				11			// 上传地图
#define CMDO_PATH_BUILD				12			// 请求线路
#define CMDO_PATH_UPLOAD			13			// 上传线路
#define CMDO_MAP_DOWN			    14          // 下载地图
#define CMDO_PATH_DOWN				15          // 下载线路
#define CMDO_SET_INIT_POSI			16          // 设置开机点
#define CMDO_STATION_NAV			29			// 图,线,站点,分部调度
#define CMDO_PASSPOINT_NAV			30			// 途经点导航
// #define CMDO_ANYPOINT_NAV_RETURN 	31		// 任意点导航+返航
// #define CMDO_SOURCE_TARGET_NAV  	129			// 图,源点到目标点导航
#define CMDO_BEGIN                  1
#define CMDO_END                    0
#define CMDO_ACK_BEGIN				1			// 响应开始/成功
#define CMDO_ACK_END				0			// 响应结束/束败
#define CMDO_ACK_LOADING            2           // 响应开始/成功,过程中相应的数据
#define CMDO_ACK_PROGRESS           3           // 当前进度值查询
/* * * * * * NetCmdObsolete [老的协议模式定义:NetCmdObsolete] * * * * * */

#define HIGH_CPU_USAGE		        1100        // CPU占用过高[>80%]
#define HIGH_MEMORY_USAGE			1200        // 内存占用过高[>80%]

#define SENSORS_GNSS_LOST			2100        // 定位设备丢失,21xx
#define SENSORS_LIDAR_LOST			2200        // 激光雷达丢失,22xx
#define SENSORS_LADAR_LOST          2300        // 超声波雷达丢失,23xx
#define SENSORS_CAMERA_LOST         2400        // 摄像头丢失,24xx
#define SENSORS_IMU_LOST            2500        // 惯性测量单元丢失,25xx
#define SENSORS_ROUTER_LOST         2600        // 4/5GCPE丢失,2600
#define SENSORS_ROUTER_WEAK         2601        // 4/5GCPE信号弱,2601
#define SENSORS_TAG_LOST			2700        // 推拉标签丢失,27xx
#define SENSORS_FC_LOST			    2800        // 飞控信号丢失,2800
#define SENSORS_FC_WEAK			    2801        // 飞控信号弱,2801
#define SENSORS_ECU_LOST			2900        // ECU失去响应,2900

#define DRIVE1_TEMPERATURE_HIGH     3101        // 驱动器1温度过高
#define DRIVE2_TEMPERATURE_HIGH     3102        // 驱动器2温度过高
#define DRIVE1_CURRENT_HIGH         3201        // 驱动器1电流过高
#define DRIVE2_CURRENT_HIGH         3202        // 驱动器2电流过高

#define AUTOPILOT_STARTUP           4000        // 自动驾驶启动中
#define AUTOPILOT_READY             4001        // 自动驾驶已就绪
#define AUTOPILOT_STARTUP_FAILED    4004        // 自动驾驶启动失败

// 枚举类，包含所有传感器警告类型
enum class SensorWarningLog {
    // 摄像头警告
    CAMERA_MALFUNCTION = 2000,
    CAMERA_OBSTRUCTED = 2001,
    CAMERA_LOW_LIGHT = 2002,
    CAMERA_OVEREXPOSURE = 2003,
    // 激光雷达警告
    LIDAR_MALFUNCTION = 2004,
    LIDAR_OBSTRUCTED = 2005,
    LIDAR_SIGNAL_INTERFERENCE = 2006,
    LIDAR_RANGE_LIMITED = 2007,
    // 毫米波雷达警告
    MILLIMETER_WAVE_RADAR_MALFUNCTION = 2008,
    MILLIMETER_WAVE_RADAR_OBSTRUCTED = 2009,
    MILLIMETER_WAVE_RADAR_WEATHER_INFLUENCE = 2010,
    // 超声波传感器警告
    ULTRASONIC_SENSOR_MALFUNCTION = 2011,
    ULTRASONIC_SENSOR_OBSTRUCTED = 2012,
    ULTRASONIC_SENSOR_RANGE_LIMITED = 2013,
    // 惯性测量单元警告
    IMU_MALFUNCTION = 2014,
    IMU_ACCURACY_DEGRADED = 2015,
    // GPS接收器警告
    GPS_SIGNAL_LOST = 2016,
    GPS_ACCURACY_LOW = 2017,
    // RFID传感器警告
    RFID_TAG_NOT_DETECTED = 2018,
    RFID_READER_MALFUNCTION = 2019,
    // 通用警告
    SENSOR_DISCONNECTED = 2020,
    SENSOR_CALIBRATION_NEEDED = 2021,
    SENSOR_OVERHEATED = 2022,
    SENSOR_POWER_FAILURE = 2023,
    SENSOR_BATTERY_LOW = 2024,
    SENSOR_BATTERY_LOST = 2025,
    SENSOR_MATCHING_RATIO_WEAK = 2026,
    SENSOR_MATCHING_RATIO_LOST = 2027,
};

enum VehicleStatus {
    // 车辆状态
    RADS_INITIALIZING = 4000,
    RADS_RUNNING = 4001,
    RADS_STOPPED = 4002,
    RADS_ACCELERATING = 4003,
    RADS_DECELERATING = 4004,
    RADS_FAULT = 4005,
    RADS_CHARGING = 4006,
    // 环境感知状态
    RADS_ROAD_RECOGNIZED = 4007,
    RADS_TRAFFIC_SIGNAL_RECOGNIZED = 4008,
    RADS_OBSTACLE_DETECTED = 4009,
    RADS_PEDESTRIAN_DETECTED = 4010,
    RADS_WEATHER_RECOGNIZED = 4011,
    // 驾驶模式
    RADS_AUTONOMOUS_MODE = 4012,
    RADS_MANUAL_MODE = 4013,
    RADS_ASSISTED_MODE = 4014,
    // 人机交互状态
    RADS_DRIVER_MONITORED = 4015,
    RADS_VOICE_COMMAND_RECEIVED = 4016,
    RADS_REMOTE_CONTROLLED = 4017,
    RADS_SYSTEM_PROMPTING = 4018,
    // 其他状态
    RADS_SAFE = 4019,
    RADS_LOCATED = 4020,
    RADS_COMMUNICATING = 4021,
    RADS_VEHICLE_OVERSPEED = 4022,
    RADS_VEHICLE_SHAKE = 4023,
    RADS_VEHICLE_COLLISION = 4024,
};

struct VehicleStatusDescription {
    VehicleStatus status;
    const char* description;
};


struct SensorDescription {
    SensorWarningLog sensor;
    const char* description;
};

// 初始化描述映射的函数
std::map<SensorWarningLog, std::string> initializeSensorDescriptions() {
    std::map<SensorWarningLog, std::string> descriptions;
    SensorDescription descs[] = {
        {SensorWarningLog::CAMERA_MALFUNCTION, "摄像头故障：无法获取图像数据"},
        {SensorWarningLog::CAMERA_OBSTRUCTED, "摄像头被遮挡：请检查摄像头清洁度和视野"},
        {SensorWarningLog::CAMERA_LOW_LIGHT, "光线不足：摄像头在低光照条件下性能受限"},
        {SensorWarningLog::CAMERA_OVEREXPOSURE, "过曝：摄像头在强光照条件下性能受限"},
        {SensorWarningLog::LIDAR_MALFUNCTION, "激光雷达故障：无法获取点云数据"},
        {SensorWarningLog::LIDAR_OBSTRUCTED, "激光雷达被遮挡：请检查激光雷达清洁度和视野"},
        {SensorWarningLog::LIDAR_SIGNAL_INTERFERENCE, "信号干扰：激光雷达受到外部干扰，数据异常"},
        {SensorWarningLog::LIDAR_RANGE_LIMITED, "探测范围受限：环境因素影响激光雷达探测距离"},
        {SensorWarningLog::MILLIMETER_WAVE_RADAR_MALFUNCTION, "毫米波雷达故障：无法获取距离和速度数据"},
        {SensorWarningLog::MILLIMETER_WAVE_RADAR_OBSTRUCTED, "毫米波雷达被遮挡：请检查雷达前方无遮挡物"},
        {SensorWarningLog::MILLIMETER_WAVE_RADAR_WEATHER_INFLUENCE, "天气影响：恶劣天气导致毫米波雷达性能下降"},
        {SensorWarningLog::ULTRASONIC_SENSOR_MALFUNCTION, "超声波传感器故障：无法获取距离数据"},
        {SensorWarningLog::ULTRASONIC_SENSOR_OBSTRUCTED, "超声波传感器被遮挡：请检查传感器前方无遮挡物"},
        {SensorWarningLog::ULTRASONIC_SENSOR_RANGE_LIMITED, "探测范围受限：超声波传感器探测距离不足"},
        {SensorWarningLog::IMU_MALFUNCTION, "惯性测量单元故障：无法获取运动状态数据"},
        {SensorWarningLog::IMU_ACCURACY_DEGRADED, "精度下降：惯性测量单元受外部因素影响，数据精度降低"},
        {SensorWarningLog::GPS_SIGNAL_LOST, "GPS信号丢失：无法获取定位信息"},
        {SensorWarningLog::GPS_ACCURACY_LOW, "GPS精度低：当前环境下GPS定位精度受限"},
        {SensorWarningLog::RFID_TAG_NOT_DETECTED, "RFID标签未检测到：请检查RFID标签是否存在和有效"},
        {SensorWarningLog::RFID_READER_MALFUNCTION, "RFID读取器故障：无法读取RFID标签信息"},
        {SensorWarningLog::SENSOR_DISCONNECTED, "传感器断开连接：请检查传感器连接状态"},
        {SensorWarningLog::SENSOR_CALIBRATION_NEEDED, "传感器需要校准：请进行传感器校准操作"},
        {SensorWarningLog::SENSOR_OVERHEATED, "传感器过热：请检查传感器散热情况"},
        {SensorWarningLog::SENSOR_POWER_FAILURE, "传感器电源故障：请检查传感器电源供应"},
        {SensorWarningLog::SENSOR_BATTERY_LOW, "动力电池电量不足：(<20%)请检查动力电源供应"},
        {SensorWarningLog::SENSOR_BATTERY_LOST, "动力电池电量不足：(<5%)请检查动力电源供应"},
        {SensorWarningLog::SENSOR_MATCHING_RATIO_WEAK, "融合定位匹配率低：(<50%),请检查激光雷达摄像头定位装置等传感器"},
        {SensorWarningLog::SENSOR_MATCHING_RATIO_LOST, "融合定位匹配率低：(<30%),请检查外部环境是否发生突变"}

    };
    for (const auto& desc : descs) {
        descriptions[desc.sensor] = desc.description;
    }
    return descriptions;
}

std::map<VehicleStatus, std::string> initializeVehicleStatusDescriptions() {
    std::map<VehicleStatus, std::string> descriptions;
    VehicleStatusDescription descs[] = {
        {VehicleStatus::RADS_INITIALIZING, "车辆系统初始化中"},
        {VehicleStatus::RADS_RUNNING, "车辆正在行驶中"},
        {VehicleStatus::RADS_STOPPED, "车辆处于静止状态，未行驶"},
        {VehicleStatus::RADS_ACCELERATING, "车辆正在加速"},
        {VehicleStatus::RADS_DECELERATING, "车辆正在减速"},
        {VehicleStatus::RADS_FAULT, "车辆发生故障，需要维修"},
        {VehicleStatus::RADS_CHARGING, "车辆正在进行充电"},
        {VehicleStatus::RADS_ROAD_RECOGNIZED, "系统能够识别当前行驶的道路"},
        {VehicleStatus::RADS_TRAFFIC_SIGNAL_RECOGNIZED, "系统能够识别交通信号灯、交通标志等"},
        {VehicleStatus::RADS_OBSTACLE_DETECTED, "系统能够检测到前方的障碍物"},
        {VehicleStatus::RADS_PEDESTRIAN_DETECTED, "系统能够检测到前方的行人"},
        {VehicleStatus::RADS_WEATHER_RECOGNIZED, "系统能够识别当前的天气状况"},
        {VehicleStatus::RADS_AUTONOMOUS_MODE, "车辆由自动驾驶系统控制行驶"},
        {VehicleStatus::RADS_MANUAL_MODE, "车辆由驾驶员手动控制行驶"},
        {VehicleStatus::RADS_ASSISTED_MODE, "自动驾驶系统辅助驾驶员进行行驶"},
        {VehicleStatus::RADS_DRIVER_MONITORED, "系统正在监控驾驶员的状态"},
        {VehicleStatus::RADS_VOICE_COMMAND_RECEIVED, "系统正在接收驾驶员的语音指令"},
        {VehicleStatus::RADS_REMOTE_CONTROLLED, "车辆正在接受远程控制中心的控制"},
        {VehicleStatus::RADS_SYSTEM_PROMPTING, "系统正在向操作人员提供提示信息"},
        {VehicleStatus::RADS_SAFE, "车辆当前处于安全状态"},
        {VehicleStatus::RADS_LOCATED, "车辆当前能够准确定位"},
        {VehicleStatus::RADS_COMMUNICATING, "车辆与自动驾驶系统或其他车辆之间的通信状态"},
        {VehicleStatus::RADS_VEHICLE_OVERSPEED, "车辆已经超速(限制最大时速)"},
        {VehicleStatus::RADS_VEHICLE_SHAKE, "车辆车体发生重度抖动"},
        {VehicleStatus::RADS_VEHICLE_COLLISION, "车辆车体发生碰撞"}
    };
    for (const auto& desc : descs) {
        descriptions[desc.status] = desc.description;
    }

    return descriptions;
}

/*
    SensorWarningLog warning = SensorWarningLog::CAMERA_MALFUNCTION;
    std::cout << "警告描述: " << getDescription(warning) << std::endl;
 */
std::string getSensorDescription(SensorWarningLog sensor) {
    static std::map<SensorWarningLog, std::string> descriptions = initializeSensorDescriptions();
    auto it = descriptions.find(sensor);
    if (it != descriptions.end()) {
        return it->second;
    } else {
        return "未知传感器警告";
    }
}

/*
    VehicleStatus status = VehicleStatus::RADS_INITIALIZING;
    std::cout << "状态描述: " << getDescription(status) << std::endl;
*/
std::string getVehicleDescription(VehicleStatus status) {
    static std::map<VehicleStatus, std::string> descriptions = initializeVehicleStatusDescriptions();
    auto it = descriptions.find(status);
    if (it != descriptions.end()) {
        return it->second;
    } else {
        return "未知车辆状态";
    }
}

// 这仅用于字符串拼接，不用于宏名生成
#define CONCAT(a, b) 		a ## b
// P
#define PI                  3.14159265358979323846
// 调试模式
#ifndef DEBUG
#define DEBUG
#endif
// 日志级别定义  
#define DEBUG_LEVEL_FATAL 4  
#define DEBUG_LEVEL_ERROR 3  
#define DEBUG_LEVEL_WARN  2  
#define DEBUG_LEVEL_INFO  1  
#define DEBUG_LEVEL_NONE  0
// 当前日志级别  
#define CURRENT_DEBUG_LEVEL DEBUG_LEVEL_ERROR
// 获取时间戳的函数  
const char* base_timestamp() {  
	static char buffer[20];  
	time_t now = time(NULL);  
	struct tm *t = localtime(&now);  
	strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", t);  
	return buffer;  
}

int64_t current_timestamp_ms() {
    struct timespec spec;
    if (clock_gettime(CLOCK_REALTIME, &spec) != 0) {
        perror("clock_gettime");
        exit(EXIT_FAILURE);
    }
    return spec.tv_sec * 1000LL + spec.tv_nsec / 1000000LL;
}

// 安全转换(string->double)
double safe_stod(const std::string& str) {
    std::stringstream ss(str);
    double result;
    ss >> result;
    if (ss.fail() || !ss.eof()) {
        return std::numeric_limits<double>::quiet_NaN();
    }
    return result;
}

// 安全转换(string->int)
double safe_stoi(const std::string& str) {
    std::stringstream ss(str);
    double result;
    ss >> result;
    if (ss.fail() || !ss.eof()) {
        return std::numeric_limits<int>::quiet_NaN();
    }
    return result;
}

// 是否是有效的网络命令
bool isValidNetCommand(const std::string& str) {
    if (str.length() < 2) {
        return false;
    }
    if (str.substr(0, 2) != "##") {
        return false;
    }
    size_t foundPos = str.find("##", 2);
    if (foundPos != std::string::npos) {
        return false;
    }
    return true;
}

// 符号分隔，生成vector
std::vector<std::string> splitStr(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(str);
    while (std::getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    if (!tokens.empty() && tokens.back().empty()) {
        tokens.pop_back();
    }
    return tokens;
}

// 构建启动命令字符串
std::string buildLaunchCommand(const std::string& package, const std::string& executable) {
	std::ostringstream oss;
	oss << "rosrun " << package << " " << executable << " &";
	return oss.str();
}
// 重新启动节点服务
bool restartNode(const std::string& launchCommand)
{
	return 0 == system(launchCommand.c_str())?true:false;
}

// 简单的XOR加密解密
class SimpleXORCipher {
    public:
        SimpleXORCipher(const std::string& key) : key_(key) {
            if (key_.size() == 0) {
                throw std::invalid_argument("Key cannot be empty");
            }
        }
        void encryptDecryptFile(const std::string& inputFile, const std::string& outputFile) {
            std::ifstream infile(inputFile, std::ios::binary);
            std::ofstream outfile(outputFile, std::ios::binary);
            if (!infile || !outfile) {
                std::cerr << "Error opening file!" << std::endl;
                return;
            }
            std::vector<char> buffer((std::istreambuf_iterator<char>(infile)), std::istreambuf_iterator<char>());
            size_t keyLen = key_.size();
            for (size_t i = 0; i < buffer.size(); ++i) {
                buffer[i] ^= key_[i % keyLen]; // XOR with the key, repeating the key as needed
            }
            outfile.write(buffer.data(), buffer.size());
            infile.close();
            outfile.close();
        }
    private:
        std::string key_;
};

// 将MD5摘要转换为十六进制字符串
std::string md5_to_hex(const unsigned char* md) {
    std::stringstream ss;
    for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
        ss << std::hex << std::setw(2) << std::setfill('0') << (int)md[i];
    }
    return ss.str();
}

// 计算文件的MD5校验和
std::string calculate_md5(const std::string& filename) {
    MD5_CTX md5_ctx;
    MD5_Init(&md5_ctx);
    std::ifstream file(filename, std::ios::binary);
    if (!file) {
        throw std::runtime_error("Unable to open file");
    }
    std::vector<char> buffer(8192);
    while (file) {
        file.read(buffer.data(), buffer.size());
        std::streamsize bytes_read = file.gcount();
        if (bytes_read > 0) {
            MD5_Update(&md5_ctx, buffer.data(), bytes_read);
        }
    }
    unsigned char md[MD5_DIGEST_LENGTH];
    MD5_Final(md, &md5_ctx);
    return md5_to_hex(md);
}

// 逗号分隔版本号
std::vector<int> splitVersion(const std::string& version) {
    std::vector<int> parts;
    std::stringstream ss(version);
    std::string part;
    while (std::getline(ss, part, '.')) {
        parts.push_back(std::stoi(part));
    }
    return parts;
}

// 比较版本号
int compareVersions(const std::string& version1, const std::string& version2) {
    std::vector<int> v1 = splitVersion(version1);
    std::vector<int> v2 = splitVersion(version2);
    size_t maxLength = std::max(v1.size(), v2.size());
    v1.resize(maxLength, 0);
    v2.resize(maxLength, 0);
    for (size_t i = 0; i < maxLength; ++i) {
        if (v1[i] < v2[i]) {
            return -1;
        } else if (v1[i] > v2[i]) {
            return 1;
        }
    }
    return 0;
}

// 判断是不是##开头的字符串协议
bool headerWith(const std::string& str) {
    if(str.size() < 2) return false;
    return str.substr(0,2) == "##";
}

// 调试宏定义  
#if CURRENT_DEBUG_LEVEL >= DEBUG_LEVEL_FATAL  
#define DEBUG_FATAL(fmt, ...) fprintf(stderr, "[%s] FATAL: " fmt "\n", base_timestamp(), ##__VA_ARGS__);  
#else  
#define DEBUG_FATAL(fmt, ...) /* No-op */  
#endif
#if CURRENT_DEBUG_LEVEL >= DEBUG_LEVEL_ERROR  
#define DEBUG_ERROR(fmt, ...) fprintf(stderr, "[%s] ERROR: " fmt "\n", base_timestamp(), ##__VA_ARGS__);  
#else  
#define DEBUG_ERROR(fmt, ...) /* No-op */  
#endif
#if CURRENT_DEBUG_LEVEL >= DEBUG_LEVEL_WARN  
#define DEBUG_WARN(fmt, ...) fprintf(stderr, "[%s] WARN: " fmt "\n", base_timestamp(), ##__VA_ARGS__);  
#else  
#define DEBUG_WARN(fmt, ...) /* No-op */  
#endif
#if CURRENT_DEBUG_LEVEL >= DEBUG_LEVEL_INFO  
#define DEBUG_INFO(fmt, ...) fprintf(stdout, "[%s] INFO: " fmt "\n", base_timestamp(), ##__VA_ARGS__);  
#else  
#define DEBUG_INFO(fmt, ...) /* No-op */  
#endif
#endif
